package com.ziytek.web.citizen.service;


import com.ziytek.web.citizen.constant.ServerConstant;
import com.ziytek.web.citizen.util.LocationUtils;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * 用户数据目录服务
 *
 * @author fenghx
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AppDataService {

    private static String APP_DATA_DIR = System.getenv("APPDATA") + File.separator;

    public String getAppDataDir() {
        return APP_DATA_DIR;
    }

    @PostConstruct
    public void appData() {
        // 获取用户数据目录
        var dataDir = System.getenv("APPDATA") + File.separator + ServerConstant.APP_DATA_JT_CABINET;
        File fi = new File(dataDir);
        if (!fi.exists()) {
            fi.mkdir();
        }

        dataDir = dataDir + File.separator + ServerConstant.APP_DATA_DATA;
        fi = new File(dataDir);
        if (!fi.exists()) {
            fi.mkdir();
        }

        //需在启动时通过 传递环境变量
        System.setProperty("APPDATA", System.getenv("APPDATA"));
        APP_DATA_DIR = dataDir;
        log.info("用户数据储存目录:{}", APP_DATA_DIR);
        init();
    }

    private void init() {
        // 获取用户数据目录
        var tarPath = getAppDataDir() + File.separator + ServerConstant.APP_DATA_DB;
        var notExist = false;
        var fi = new File(tarPath);
        if (!fi.exists()) {
            notExist = true;
        }

        if (!notExist) {
            var del = deleteFolder(new File(LocationUtils.getLocation() + File.separator + ServerConstant.APP_DATA_DB));
            log.info("删除DB源文件结果[{}]", del);
            return;
        }

        // 数据库DB文件迁移
        // 单文件拷贝（覆盖模式）
        //FileCopyUtils.copy(sourceFile.getInputStream(), new FileOutputStream(targetFile));

        try {
            var souPath = LocationUtils.getLocation() + File.separator + ServerConstant.APP_DATA_DB;
            log.info("db文件拷贝:{} -> {}", souPath, tarPath);
            var sourceDirPath = Paths.get(souPath);
            var targetDirPath = Paths.get(tarPath);
            // 文件夹递归拷贝（需手动处理目录结构）
            Files.walk(sourceDirPath)
                    .forEach(sourcePath -> {
                        var targetPath = targetDirPath.resolve(sourceDirPath.relativize(sourcePath));
                        try {
                            Files.createDirectories(targetPath.getParent());
                            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
                        } catch (IOException e) {
                            throw new RuntimeException("拷贝失败：" + e.getMessage());
                        }
                    });

            // 拷贝完毕删除元文件
            var del = deleteFolder(new File(souPath));
            log.info("首次删除DB源文件:{}", del);
        } catch (Exception e) {
            log.error("db文件拷贝失败", e);
        }
    }

    private boolean deleteFolder(File folder) {
        if (null == folder || !folder.exists()) {
            return true;
        }

        var files = folder.listFiles();
        if (null != files) {
            for (var file : files) {
                if (file.isDirectory()) {
                    // 递归删除子目录
                    deleteFolder(file);
                } else {
                    // 删除文件
                    file.delete();
                }
            }
        }
        // 删除空目录
        return folder.delete();
    }
}
